// pages/addSchedule/addSchedule.js
// pages/scheduleManage/scheduleManage.js
var app = getApp();
let load = true ;
let target_id = [];//选中的订单
Page({

  /**
   * 页面的初始数据
   */
  data: {
    page: 1,
    pageSize: 10,
    chooseDate: '', //上一个页面传过来的选中的日期
    orderList: [],
    empty: true,
    hasMore: false,
    loading: false,
    loadShow: false,
    token: wx.getStorageSync('token'),
    lat1: '',
    lng1: '',
    reasonIndex: "",
    reasonShow: true,//
    chargebackId: '',//退还订单号
    remarks: '',//退还备注
    tipShow: true,//
    dropShow: true,//上门

    searchKey: '', //搜索关键字
    ordertypeList: [], //订单类型列表
    selectTypeid: [], //选中的订单类型ID
    distanceList: [], //距离列表
    selectDistance: '', //选中的距离
    isMaskShow: false,//遮罩层显隐
    move: 0,//筛选弹窗
    screenShow: false,//筛选模块显隐,

    callShow: false,//拨打电话弹窗显示
    callItem: '',// 点击拨打的工单详情
    callIndex: 0,//选择联系人|紧急联系人
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.setData({
      chooseDate: options.date
    })
    that.getBussinessType();
    that.getDistanceList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    that.getRepairOrder();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this;
    // 当没有数据时,不再请求
    var hasMore = that.data.hasMore;
    if (!hasMore) {
      return false;
    }

    var page = that.data.page + 1;
    that.setData({
      page: page,
      loading: true
    })
    that.getRepairOrder();
  },



  //获取日程数据
  getRepairOrder(key) {
    var that = this;
    app.ajax({
      url: "Engineer/Order/getRepairOrder",
      load: load,
      msg: '数据加载中...',
      data: {
        work_order_status: [8,9],
        business_id: that.data.selectTypeid,
        distance_range: that.data.selectDistance,
        searchKey: key || that.data.searchKey,
        page: that.data.page,
        row: that.data.pageSize
      },
      success: function (res) {
        if (res.data.code == 1000) {
          if (that.data.page == 1) {
            that.setData({
              orderList: res.data.data.work_list,
              empty: false
            });
          } else {
            that.setData({
              orderList: that.data.orderList.concat(res.data.data.work_list),
              empty: false
            });
          }
          for (var index in that.data.orderList) {
            var checkbox = "orderList[" + index + "].checkbox";
            that.setData({
              [checkbox]: false
            })
          }
          // 是否加载更多
          var hasMore = true;
          if (res.data.data.work_list.length < that.data.pageSize) {
            hasMore = false;
          }
          that.setData({
            hasMore: hasMore,
            loading: false
          });
          load = false;
        } else {
          if (that.data.page == 1) {
            that.setData({
              hasMore: false,
              loading: false,
              empty: true
            })
          } else {
            that.setData({
              hasMore: false,
              loading: false,
              empty: false
            })
          }
        }
        that.setData({
          loadShow: true
        })
      }
    })
  },
  // 输入搜索字段
  inputSearch: function (e) {
    var that = this;
    var searchKey = e.detail.value;
    that.setData({
      searchKey: searchKey
    });
  },
  //小键盘直接搜索
  searchOrder: function (e) {
    var that = this;
    var key = e.detail.value;
    // if (key == '' || key == null) {
    //   app.showToast("请输入搜索关键字", "none", 2000, function () { });
    //   return;
    // }
    that.setData({
      searchKey: key,
      orderList: [],
      page: 1,
      empty: true,
      hasMore: false,
      loading: false,
      loadShow: false
    })
    load = true;
    that.getRepairOrder(key);
  },
  //点击搜索图标搜索
  searchOrder2: function () {
    var that = this;
    var key = that.data.searchKey;
    that.setData({
      orderList: [],
      page: 1,
      empty: true,
      hasMore: false,
      loading: false,
      loadShow: false
    })
    load = true;
    that.getRepairOrder(key);
  },
  //确认预约时间
  amendTime(e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/order/amendTime/amendTime?id=' + id,
    })
  },
  //退还订单
  chargeback(e) {
    let that = this;
    let reasonShow = false;
    let id = e.currentTarget.dataset.id;
    that.setData({
      reasonShow: reasonShow,
      chargebackId: id
    })
  },
  //退还原因
  bindPickerChange: function (e) {
    let that = this;
    let reasonIndex = e.detail.value;
    that.setData({
      reasonIndex: reasonIndex
    })
  },
  //退换备注
  inputRemarks: function (e) {
    var that = this;
    var remarks = e.detail.value;
    that.setData({
      remarks: remarks
    });
  },
  //确定退还
  confirm: function (e) {
    let that = this;
    let reasonShow = true;
    let tipShow = false;
    var id = that.data.chargebackId;
    var reasonIndex = that.data.reasonIndex;
    var remarks = that.data.remarks;
//    app.saveFormId(e.detail.formId);
    if (reasonIndex == '' || remarks == '') {
      app.showToast("请填写完整信息", "none", 2000, function () { });
      return;
    }
    app.ajax({
      url: 'Engineer/Workorder/backOrderApply',
      data: {
        work_order_id: id,
        reason_id: reasonIndex,
        remark: remarks
      },
      header: {
        'token': that.data.token
      },
      success: function (res) {
        if (res.data.code == 1000) {
          app.showToast("退单成功", "none", 2000, function () { });
        } else {
          app.showToast(res.data.message, "none", 2000, function () { });

        }

      }
    })
    that.setData({
      reasonShow: reasonShow,
      tipShow: tipShow,
      remarks: '',
      reasonIndex: ''
    })
    timer = setTimeout(function () {
      let tipShow = true;
      that.setData({
        tipShow: tipShow
      })
      that.getOrderList();
    }, 2000);
  },
  //取消退还
  cancel: function () {
    let that = this;
    let reasonShow = true;
    that.setData({
      reasonShow: reasonShow,
      remarks: '',
      reasonIndex: ''
    })
  },
  //查看详情
  orderDetail(e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/order/orderDetail/orderDetail?id=' + id,
    })
  },
  //上门
  dropIn: function (e) {
    let that = this;
    let dropShow = false;
    var id = e.currentTarget.dataset.id;
    var lat1, lng1;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        lat1 = res.latitude;
        lng1 = res.longitude;

        that.setData({
          dropShow: dropShow,
          work_order_id: id,
          lat1: lat1,
          lng1: lng1
        })
      }
    });
  },
  //确定上门
  dropConfirm: function (e) {
    let that = this;
    let dropShow = true;
    var id = that.data.work_order_id;
    var lat1 = that.data.lat1;
    var lng1 = that.data.lng1;
    //app.saveFormId(e.detail.formId);
    app.ajax({
      url: 'Engineer/Workorder/goHome',
      data: {
        work_order_id: id,
        lat: lat1,
        lng: lng1
      },
      header: {
        'token': that.data.token
      },
      success: function (res) {
        if (res.data.code == 1000) {
          app.showToast("确认成功", "none", 2000, function () { });
          wx.setStorageSync('tabIndex', 2);
          that.getOrderList();
        } else {
          app.showToast(res.data.message, "none", 2000, function () { });
        }
      }
    })

    that.setData({
      dropShow: dropShow
    })
  },
  //取消上门
  dropCancel: function () {
    let that = this;
    let dropShow = true;
    that.setData({
      dropShow: dropShow
    })
  },
  // 确认安装地址
  confirmAddress(e) {
    var that = this;
    var order_id = e.currentTarget.dataset.id;
    var type = e.currentTarget.dataset.type;
    if (type != 2) {
      type = 1;
    }
    wx.navigateTo({
      url: '/pages/order/confirmAddress/confirmAddress?order_id=' + order_id + '&type=' + type,
    })
  },
  // 选择订单
  chooseOrder(e){
    var that = this;
    let selArr = target_id;
    let selId = e.currentTarget.dataset.id;
    let dataList = that.data.orderList;
    let index = target_id.indexOf(selId);
    if (index < 0) {
      // if (target_id.length >= 12) {
      //   app.showToast('不能超过12个');
      //   return
      // } else {
        selArr.push(selId);
        dataList.map((value) => {
          if (value.work_order_id == selId) {
            value.checkbox = true
          }
        })
      // }
    } else {
      dataList.map((value) => {
        if (value.work_order_id == selId) {
          value.checkbox = false
        }
      })
      selArr.splice(index, 1)
    }
    target_id = selArr;
    that.setData({
      orderList: dataList
    })
  },
  // 确认添加到日程
  sure() {
    var that = this;
    app.ajax({
      url: 'Engineer/Schedule/arrangeSchedule',
      data: {
        schedule_time: that.data.chooseDate,
        target_id: target_id
      },
      success: function (res) {
        if (res.data.code == 1000) {
          app.showToast(res.data.message, "none", 1000, function () { 
            // 返回上一页
            wx.navigateBack();
          });
        } else {
          app.showToast(res.data.message, "none", 1000, function () { });
        }
      }
    })
    
  },


  // 阻止遮罩滚动
  myCatchTouch: function () {
    return;
  },
  // 获取订单类型列表
  getBussinessType: function () {
    var that = this;
    app.ajax({
      url: 'Common/Common/getBussinessType',
      data: {},
      header: {
        'token': this.data.token
      },
      success: function (res) {
        if (res.data.code == 1000) {
          that.setData({
            screenTypes: res.data.data
          })
        } else {
          // 没有数据
        }
      }
    })
  },
  // 获取距离列表
  getDistanceList: function () {
    var that = this;
    app.ajax({
      url: 'Common/Common/getServiceConfig',
      data: {
        key: 'distance'
      },
      success: function (res) {
        if (res.data.code == 1000) {
          that.setData({
            distanceList: res.data.data
          })
        } else {
          // 没有数据
        }
      }
    })
  },
  // 筛选模块显、隐
  chooseType: function () {
    var that = this;
    if (that.data.screenShow == false) {
      that.setData({
        screenShow: true,
        isMaskShow: true,
        move: 0
      })
    } else {
      that.setData({
        move: 1,
      })
      setTimeout(function () {
        that.setData({
          screenShow: false,
          isMaskShow: false,
        })
      }, 500)
    }
  },
  // 关闭弹窗
  closeMask() {
    var that = this;
    that.setData({
      move: 1,
    })
    setTimeout(function () {
      that.setData({
        screenShow: false,
        isMaskShow: false,
      })
    }, 500)
  },

  //选择优惠活动分类
  ordertypeChoose(e) {
    var that = this;
    var obj = that.data.selectTypeid;
    var id = e.currentTarget.dataset.id;
    if (that.data.selectTypeid.indexOf(id) < 0) {
      obj.push(id);
    } else {
      obj.splice(that.data.selectTypeid.indexOf(id), 1)
    }
    console.log(obj);
    that.setData({
      selectTypeid: obj
    })
  },
  //选择距离分类
  distanceChoose(e) {
    var that = this;
    that.setData({
      selectDistance: e.currentTarget.dataset.id
    })
  },
  //确定选择的活动和距离
  sureChoose() {
    var that = this;
    that.setData({
      orderList: [],
      page: 1
    })
    that.closeMask();
    that.getRepairOrder();
  },
  //重置
  reset() {
    var that = this;
    that.setData({
      orderList: [],
      selectTypeid: [],
      selectDistance: '',
      page: 1
    })
    that.getRepairOrder();
  },

  // 打开拨打电话弹窗
  openCall(e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    console.log('index', index);
    var orderList = that.data.orderList;
    var item = orderList[index];
    console.log('item', item)
    that.setData({
      callShow: true,
      callItem: item,
      callIndex: 0,
    })
  },
  // 关闭拨打电话弹窗
  cancelCall() {
    var that = this;
    that.setData({
      callShow: false,
      callItem: false
    })
  },
  // 跳转紧急联系人
  goEmergency() {
    var that = this;
    var callItem = that.data.callItem;
    wx.navigateTo({
      url: '/pages/order/emergencyContact/emergencyContact?user_id=' + callItem.user_id + '&work_order_id=' + callItem.work_order_id + '&emergency_contact=' + JSON.stringify(callItem.emergency_contact),
    })
    that.cancelCall();
  },
  // 切换选择联系人|紧急联系人
  callChoose(e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    that.setData({
      callIndex: index
    })
  },
  // 确认选中拨打电话
  sureTelphone() {
    var that = this;
    var index = that.data.callIndex;
    var callItem = that.data.callItem;
    var number = callItem.contact_number;
    if (index == 1) {
      number = callItem.emergency_contact.tel
    }
    wx.makePhoneCall({
      phoneNumber: number,
    })
    that.cancelCall();
  },
  //联系他
  telPhone: function (e) {
    let phone = e.currentTarget.dataset.phone;
    wx.makePhoneCall({
      phoneNumber: phone,
    })
  },
  //跳转添加日程
  addDate() {
    var that = this;
    wx.navigateTo({
      url: '/pages/subpackage/pages/date/addSchedule/addSchedule?date=' + that.data.chooseDate,
    })
  },

})